import 'dart:convert';
import 'dart:developer';

import 'package:crypto/crypto.dart';
import 'package:intl/intl.dart';

class XfAuthUtils {
  //实时评测
  static const String hostUrl = "https://ise-api.xfyun.cn/v2/open-ise";

  // appId
  static const String appId = "7e116a32";

  // appKey
  static const String apiKey = "44a9aa8d6f490b19cdbc8127f772e8f4";

  // 秘钥
  static const String apiSecret = "ZDE0MTIxN2I2YzA1ZmExMjY5ZWFkZTQ0";

  //获取授权地址
  static String getAuthUrl({String? ip}){
    Uri url = Uri.parse(hostUrl);


    // var ip = "47.119.24.249";
    log('获取到讯飞host : $ip');

    DateTime dateTime = DateTime.now().toUtc();
    String date = DateFormat('EEE, dd MMM yyyy HH:mm:ss \'GMT\'', 'en_US')
        .format(dateTime);

    String builder =
        "host: ${url.host}\n" + "date: $date\n" + "GET ${url.path} HTTP/1.1";

    var bytes = utf8.encode(builder);
    Hmac hmac = Hmac(sha256, utf8.encode(apiSecret));
    Digest sha = hmac.convert(bytes);

    String authorization =
        'api_key="$apiKey", algorithm="hmac-sha256", headers="host date request-line", signature="${base64.encode(sha.bytes)}"';

    Uri httpUrl =
        Uri.parse("https://${ip ?? url.host}:80${url.path}").replace(queryParameters: {
      'authorization': base64.encode(utf8.encode(authorization)),
      'date': date,
      'host': url.host,
    });

    return httpUrl.toString().replaceFirst("https", "ws");
  }
}
